﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using DevExpress.XtraGrid.Demos.util;
using Luna小店.DTO;
using mendian;
using Luna小店.UC.门店下单.DTO;
using DevExpress.XtraEditors.Popup;
using DevExpress.XtraGrid.Editors;
using DevExpress.XtraLayout;
using DevExpress.Utils.Win;
using Luna小店.UC.辅料;
using DiaoPaiDaYin;
using Luna小店.UC.设计点;
using Luna小店.UC.门店下单.form;
using Luna小店.DTO.坚山;
using Luna小店.UC.款式异常;
using Luna小店.service;
using Luna小店.UC.样品管理.样品下单新.service;
using System.Net;
using Luna小店.UC.款式管理.service;
using Luna小店.UC.面料库存.库存记录.service;

namespace Luna小店.UC.样品管理.样品下单新
{
    public partial class Form样品下单详情 : DevExpress.XtraBars.Ribbon.RibbonForm
    {
        public DTOStyleMeasureItems dTOStyleMeasureItems { get; set; } = new DTOStyleMeasureItems();
        private String 款式 { get; set; }
        private String 款号 { get; set; }
        private String styleId;
        private String categoryId;
        private List<面料选择> 面料选择s = new List<面料选择>();
        private List<DTO款式备选> DTO款式备选s = new List<DTO款式备选>();
        public List<StyleCategoryDTO> styleCategoryDTOs = new List<StyleCategoryDTO>();
        private DataTable STYLE_CATEGORY;
        public StyleAccessoryItemsDTO styleAccessoryItemsDTO;//辅料保存用dto
        public List<ContrastForUCDto> contrastForUCDtos = new List<ContrastForUCDto>();
        private String 版型名称 { get; set; }
        private String 款式类别 { get; set; }
        private String 制作工艺 { get; set; }
        
        private Frm样品下单 frm;
        public DTO坚山款式 dto坚山款式 { get; set; }
        public 门店下单选款式Model model = new 门店下单选款式Model();

        private String formId;
        public Form样品下单详情()
        {
            InitializeComponent();
        }
        public Form样品下单详情(String formId,Frm样品下单 frm)
        {
            InitializeComponent();
            this.formId = formId;
            this.frm = frm;
            this.dto坚山款式 = new DTO坚山款式();
            this.dto坚山款式.刺绣设计点s = new List<string>();
            this.dto坚山款式.刺绣设计点s = FunctionHelper.JsonDeserialization<List<String>>("[\"4SMT\",\"4SMO\",\"4SMC\",\"4SMP\",\"4SMS\"]");
            this.STYLE_CATEGORY = StyleService.GetAllSTYLE_CATEGORY();
            this.styleCategoryDTOs = FunctionHelper.JsonDeserialization<List<StyleCategoryDTO>>(RestCall.httpGetMethod(URL.接口url + "/style/getStyleCategoryAll"));
            this.searchLookUpEdit款式类别.Properties.DataSource = this.styleCategoryDTOs;
            this.searchLookUpEdit款式.Properties.DataSource = this.DTO款式备选s;
            this.面料选择s = FunctionHelper.JsonDeserialization<List<面料选择>>(RestCall.httpGetMethod(URL.接口url + "/material/getMaterialOrderIndexAll"));
            this.searchLookUpEdit面料.Properties.DataSource = this.面料选择s;
            
            this.gridControl备注.DataSource = 样品下单Service.get备注项目详情(this.formId);
        }

        #region 选择面料
        /// <summary>
        /// 绑定清空事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void searchLookUpEdit面料_Popup(object sender, EventArgs e)
        {
            //得到当前SearchLookUpEdit弹出窗体
            PopupSearchLookUpEditForm form = (sender as IPopupControl).PopupWindow as PopupSearchLookUpEditForm;
            SearchEditLookUpPopup popup = form.Controls.OfType<SearchEditLookUpPopup>().FirstOrDefault();
            LayoutControl layout = popup.Controls.OfType<LayoutControl>().FirstOrDefault();
            //如果窗体内空间没有确认按钮，则自定义确认simplebutton，取消simplebutton，选中结果label
            if (layout.Controls.OfType<Control>().Where(ct => ct.Name == "btOK").FirstOrDefault() == null)
            {
                //得到空的空间
                EmptySpaceItem a = layout.Items.Where(it => it.TypeName == "EmptySpaceItem").FirstOrDefault() as EmptySpaceItem;

                //得到取消按钮，重写点击事件
                Control clearBtn = layout.Controls.OfType<Control>().Where(ct => ct.Name == "btClear").FirstOrDefault();
                LayoutControlItem clearLCI = (LayoutControlItem)layout.GetItemByControl(clearBtn);
                clearBtn.Click += clearBtn_Click;

                //添加一个simplebutton控件(确认按钮)
                LayoutControlItem myLCI = (LayoutControlItem)clearLCI.Owner.CreateLayoutItem(clearLCI.Parent);
                myLCI.TextVisible = false;
            }
        }
        /// <summary>
        /// 点击选择后的行为
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void searchLookUpEdit面料View_Click(object sender, EventArgs e)
        {
            var a = this.searchLookUpEdit面料.Properties.View.GetSelectedRows();
            foreach (int rowHandle in a)
            {
                Frm面料选择.mianliaoid = this.searchLookUpEdit面料.Properties.View.GetRowCellValue(rowHandle, "materialId").ToString();
                Frm面料选择.mianliao = this.searchLookUpEdit面料.Properties.View.GetRowCellValue(rowHandle, "materialNameCn").ToString();
                this.model.Dto定制下单.SYTLE_FABRIC_ID = this.searchLookUpEdit面料.Properties.View.GetRowCellValue(rowHandle, "materialId").ToString();
                Frm面料选择.mianliaocd = this.searchLookUpEdit面料.Properties.View.GetRowCellValue(rowHandle, "materialCode").ToString();
                this.pictureBox面料.LoadAsync(面料记录Service.get面料图(Frm面料选择.mianliaocd));
                this.textBox成分.Clear();
                this.textBox成分.Text = this.searchLookUpEdit面料.Properties.View.GetRowCellValue(rowHandle, "materialComposition").ToString();
            }
        }

        /// <summary>
        /// 清除按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void clearBtn_Click(object sender, EventArgs e)
        {
            this.searchLookUpEdit面料.ToolTip = null;
            searchLookUpEdit面料.EditValue = null;
        }
        /// <summary>
        /// 选完之后的显示
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void searchLookUpEdit面料_CustomDisplayText(object sender, DevExpress.XtraEditors.Controls.CustomDisplayTextEventArgs e)
        {
            if (null != e.Value)
                e.DisplayText = Frm面料选择.mianliaocd + ":" + Frm面料选择.mianliao;
        }
        #endregion

        #region 选择款式类别
        /// <summary>
        /// 绑定清空事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void searchLookUpEdit款式类别_Popup(object sender, EventArgs e)
        {
            //得到当前SearchLookUpEdit弹出窗体
            PopupSearchLookUpEditForm form = (sender as IPopupControl).PopupWindow as PopupSearchLookUpEditForm;
            SearchEditLookUpPopup popup = form.Controls.OfType<SearchEditLookUpPopup>().FirstOrDefault();
            LayoutControl layout = popup.Controls.OfType<LayoutControl>().FirstOrDefault();
            //如果窗体内空间没有确认按钮，则自定义确认simplebutton，取消simplebutton，选中结果label
            if (layout.Controls.OfType<Control>().Where(ct => ct.Name == "btOK").FirstOrDefault() == null)
            {
                //得到空的空间
                EmptySpaceItem a = layout.Items.Where(it => it.TypeName == "EmptySpaceItem").FirstOrDefault() as EmptySpaceItem;

                //得到取消按钮，重写点击事件
                Control clearBtn = layout.Controls.OfType<Control>().Where(ct => ct.Name == "btClear").FirstOrDefault();
                LayoutControlItem clearLCI = (LayoutControlItem)layout.GetItemByControl(clearBtn);
                clearBtn.Click += clearBtn款式类别_Click;

                //添加一个simplebutton控件(确认按钮)
                LayoutControlItem myLCI = (LayoutControlItem)clearLCI.Owner.CreateLayoutItem(clearLCI.Parent);
                myLCI.TextVisible = false;
            }
        }
        /// <summary>
        /// 点击选择后的行为
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void searchLookUpEdit款式类别View_Click(object sender, EventArgs e)
        {
            var a = this.searchLookUpEdit款式类别.Properties.View.GetSelectedRows();
            foreach (int rowHandle in a)
            {
                this.categoryId = this.searchLookUpEdit款式类别.Properties.View.GetRowCellValue(rowHandle, "id").ToString();
                this.款式类别 = this.searchLookUpEdit款式类别.Properties.View.GetRowCellValue(rowHandle, "name").ToString();
                if (this.searchLookUpEdit款式类别.Properties.View.GetRowCellValue(rowHandle, "code").ToString().Contains("STYLE_CATEGORY-"))
                {
                    this.model.Dto定制下单.STYLE_CATEGORY_CD = this.searchLookUpEdit款式类别.Properties.View.GetRowCellValue(rowHandle, "code").ToString();
                }
                else
                {
                    this.model.Dto定制下单.STYLE_CATEGORY_CD = "STYLE_CATEGORY-" + this.searchLookUpEdit款式类别.Properties.View.GetRowCellValue(rowHandle, "code").ToString();
                }
                this.DTO款式备选s = FunctionHelper.JsonDeserialization<List<DTO款式备选>>(RestCall.httpGetMethod(URL.接口url + "/style/getStyleMapByCategory?categoryId=" + this.categoryId));
                this.searchLookUpEdit款式.Properties.DataSource = this.DTO款式备选s;
                this.gridView4.RefreshData();
                this.布辅料控件();
            }
        }

        /// <summary>
        /// 清除按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void clearBtn款式类别_Click(object sender, EventArgs e)
        {
            this.searchLookUpEdit款式类别.ToolTip = null;
            searchLookUpEdit款式类别.EditValue = null;
        }
        /// <summary>
        /// 选完之后的显示
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void searchLookUpEdit款式类别_CustomDisplayText(object sender, DevExpress.XtraEditors.Controls.CustomDisplayTextEventArgs e)
        {
            if (null != e.Value)
                e.DisplayText = this.款式类别;
        }
        #endregion

        #region 选择参考款式
        /// <summary>
        /// 绑定清空事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void searchLookUpEdit款式_Popup(object sender, EventArgs e)
        {
            //得到当前SearchLookUpEdit弹出窗体
            PopupSearchLookUpEditForm form = (sender as IPopupControl).PopupWindow as PopupSearchLookUpEditForm;
            SearchEditLookUpPopup popup = form.Controls.OfType<SearchEditLookUpPopup>().FirstOrDefault();
            LayoutControl layout = popup.Controls.OfType<LayoutControl>().FirstOrDefault();
            //如果窗体内空间没有确认按钮，则自定义确认simplebutton，取消simplebutton，选中结果label
            if (layout.Controls.OfType<Control>().Where(ct => ct.Name == "btOK").FirstOrDefault() == null)
            {
                //得到空的空间
                EmptySpaceItem a = layout.Items.Where(it => it.TypeName == "EmptySpaceItem").FirstOrDefault() as EmptySpaceItem;

                //得到取消按钮，重写点击事件
                Control clearBtn = layout.Controls.OfType<Control>().Where(ct => ct.Name == "btClear").FirstOrDefault();
                LayoutControlItem clearLCI = (LayoutControlItem)layout.GetItemByControl(clearBtn);
                clearBtn.Click += clearBtn款式_Click;

                //添加一个simplebutton控件(确认按钮)
                LayoutControlItem myLCI = (LayoutControlItem)clearLCI.Owner.CreateLayoutItem(clearLCI.Parent);
                myLCI.TextVisible = false;
            }
        }
        /// <summary>
        /// 点击选择后的行为
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void searchLookUpEdit款式View_RowCellClick(object sender, DevExpress.XtraGrid.Views.Grid.RowCellClickEventArgs e)
        {
            this.styleId = FunctionHelper.GetgridViewValue(this.searchLookUpEdit款式.Properties.View, e.RowHandle, "styleId").ToString();
            this.款式 = FunctionHelper.GetgridViewValue(this.searchLookUpEdit款式.Properties.View, e.RowHandle, "name").ToString();
            this.款号 = FunctionHelper.GetgridViewValue(this.searchLookUpEdit款式.Properties.View, e.RowHandle, "code").ToString();
            this.textBox款号.Text = this.款号;
            this.textBox款名.Text = this.款式;
            try { this.pictureBox款式.LoadAsync(款式Service.get款式图(this.styleId)); } catch { }

            this.model.Dto定制下单.Style_Id = FunctionHelper.GetgridViewValue(this.searchLookUpEdit款式.Properties.View, e.RowHandle, "styleId").ToString();
            //this.model.Dto定制下单.Dto设计点s.Clear();
            //this.initNavigationPage(new UC设计点(this.model.Dto定制下单.Dto设计点s, this.model.Dto定制下单.Style_Id, this.dto坚山款式));
            //DataRow dr = SQLmtm.GetDataRow("SELECT * FROM s_style_p WHERE SYS_STYLE_ID='" + this.model.Dto定制下单.Style_Id + "'");
            //this.model.Dto定制下单.build选中款式(dr["SYS_STYLE_ID"].ToString(), this.model.Dto定制下单.STYLE_CATEGORY_CD, dr["STYLE_FIT_CD"].ToString(), dr["STYLE_SIZE_GROUP_CD"].ToString(), "", dr["STYLE_MAKE_TYPE"].ToString());//添加选中款式数据
            //foreach (DataRow drCATEGORY in this.STYLE_CATEGORY.Rows)
            //{
            //    if (drCATEGORY["CD"].ToString().Equals(this.model.Dto定制下单.STYLE_CATEGORY_CD))
            //    {
            //        break;
            //    }
            //}
            //this.布辅料控件();

            //this.model.build款式全尺寸(this.model.Dto定制下单.Style_Id);
            //Frm定制下单修改尺寸.stylesizedt = StyleService.StyleCombobox(this.model.Dto定制下单.Style_Id);
            //this.chicun01.Items.Clear();
            //List<String> 尺码 = new List<string>();
            //尺码 = FunctionHelper.JsonDeserialization<List<String>>(RestCall.httpGetMethod(URL.接口url + "/size/findSizeCdByStyleId?styleId=" + this.model.Dto定制下单.Style_Id));
            //foreach (String str in 尺码)
            //{
            //    this.chicun01.Items.Add(str);
            //}
        }
        /// <summary>
        /// 清除按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void clearBtn款式_Click(object sender, EventArgs e)
        {
            this.searchLookUpEdit款式.ToolTip = null;
            searchLookUpEdit款式.EditValue = null;
        }
        /// <summary>
        /// 选完之后的显示
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void searchLookUpEdit款式_CustomDisplayText(object sender, DevExpress.XtraEditors.Controls.CustomDisplayTextEventArgs e)
        {
            if (null != e.Value)
                e.DisplayText = this.款式;
        }
        #endregion

        private void chicun01_SelectedIndexChanged(object sender, EventArgs e)
        {
            //this.model.build选中尺寸(this.chicun01.Text.Trim(), this.model.Dto定制下单.Style_Id, Frm定制下单修改尺寸.stylesizedt);
            //this.model.Dto定制下单.STYLE_SIZE_CD = "IGS_GROUP_SIZE-" + this.chicun01.Text.Trim();
            //String json = RestCall.httpGetMethod(URL.接口url + "/style/generateStyleMeasureItems?SIZE_CD=" + this.model.Dto定制下单.STYLE_SIZE_CD + "&styleID=" + this.model.Dto定制下单.Style_Id + "&categoryId=" + this.categoryId);
            //this.dTOStyleMeasureItems = FunctionHelper.JsonDeserialization<DTOStyleMeasureItems>(json);
            //this.treeList尺寸.DataSource = this.dTOStyleMeasureItems.measureItemDTOS;
            //this.treeList尺寸.Refresh();
        }
        private void barButtonItem1_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            DialogResult dialogResult = MessageBox.Show("确认保存吗？", "保存", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            if (dialogResult == DialogResult.Yes)
            {
                this.model.Dto定制下单.STYLE_NAME_CN = this.textBox款号.Text + " " + this.textBox款名.Text;
                this.model.Dto定制下单.Delete空设计点();
                this.model.Dto定制下单.build数量(this.numericUpDown数量.Value.ToString());
                this.model.Dto定制下单.formId = this.formId;
                this.model.Dto定制下单.STYLE_SIZE_CD = "IGS_GROUP_SIZE-" + this.comboBox尺寸.Text.Trim();
                this.model.build尺寸保存(this.dTOStyleMeasureItems);//尺寸保存
                
                //this.model.Dto定制下单.ORDER_NUMBER = Convert.ToInt32(this.barEditItemNumber.EditValue);
                //ImpService.DynamicSaveSize(this, this.model.Dto定制下单);//尺寸保存
                //this.model.build尺寸保存();//尺寸保存
                //this.model.build尺寸保存(this.dTOStyleMeasureItems);//尺寸保存
                //ImpService.DynamicSaveDesign(this, this.model.Dto定制下单);//设计点保存
                //try
                //{
                //    //  校验订单
                //    this.model.verify订单();
                //}
                //catch (Exception ex)
                //{
                //    MessageBox.Show(ex.Message);
                //    return;
                //}
                //辅料保存
                this.styleAccessoryItemsDTO = new StyleAccessoryItemsDTO(this.model.Dto定制下单.STYLE_NAME_CN, this.contrastForUCDtos);
                this.model.Dto定制下单.sessionId = this.model.sessionId;
                this.frm.buildOrderModel(this.model.Dto定制下单, this.styleAccessoryItemsDTO, Luna小店.model.Enum订单类型.样衣订单);
                this.frm.refreshGridControl();
                //this.addPics();

                MessageBox.Show("保存成功");
                this.Close();
            }
        }

        private void numericUpDown数量_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (((NumericUpDown)sender).Text.Trim().IndexOf('.') > -1)
            {
                if (((NumericUpDown)sender).Text.Trim().Substring(((NumericUpDown)sender).Text.Trim().IndexOf('.') + 1).Length >= 0)//定义小数位
                {
                    if (!char.IsDigit(e.KeyChar))
                    {
                        e.Handled = false;
                    }
                    else
                    {
                        e.Handled = true;
                    }
                }
            }
        }

        /// <summary>
        /// 初始化导航
        /// </summary>
        /// <param name="uC"></param>
        private void initNavigationPage(XtraUserControl uC)
        {
            uC.Dock = DockStyle.Fill;
            //this.dockPanel设计点.Controls.Clear();
            //this.dockPanel设计点.Controls.Add(uC);
        }

        private void numericUpDown1_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (((NumericUpDown)sender).Text.Trim().IndexOf('.') > -1)
            {
                if (((NumericUpDown)sender).Text.Trim().Substring(((NumericUpDown)sender).Text.Trim().IndexOf('.') + 1).Length >= 0)//定义小数位
                {
                    if (!char.IsDigit(e.KeyChar))
                    {
                        e.Handled = false;
                    }
                    else
                    {
                        e.Handled = true;
                    }
                }
            }
        }


        private void 布辅料控件()
        {
            try
            {
                List<AccessoryItemDTO> accessoryItemDTOs = new List<AccessoryItemDTO>();
                String jsonAccessoryItemDTO = RestCall.httpGetMethod(URL.接口url + "/acc/generateQCItem?styleCategory=" + this.model.Dto定制下单.STYLE_CATEGORY_CD);
                accessoryItemDTOs = FunctionHelper.JsonDeserialization<List<AccessoryItemDTO>>(jsonAccessoryItemDTO);
                this.contrastForUCDtos.Clear();
                foreach (AccessoryItemDTO dto in accessoryItemDTOs)
                {
                    this.contrastForUCDtos.Add(new ContrastForUCDto(dto, new List<DtoForChooseContrasts>()));
                }
                String str = FunctionHelper.JsonSerialization(contrastForUCDtos);
            }
            catch { }
        }

        private void treeList尺寸_CellValueChanged(object sender, DevExpress.XtraTreeList.CellValueChangedEventArgs e)
        {
            //this.dTOStyleMeasureItems.build算(this.treeList尺寸.FocusedNode["id"].ToString(), e.Column.FieldName, e.Value.ToString());
            //this.treeList尺寸.DataSource = this.dTOStyleMeasureItems.measureItemDTOS;
            //this.treeList尺寸.Refresh();
        }

        private void treeList尺寸_ValidatingEditor(object sender, DevExpress.XtraEditors.Controls.BaseContainerValidateEditorEventArgs e)
        {
            //if (this.treeList尺寸.FocusedColumn == this.treeListColumn加 || this.treeList尺寸.FocusedColumn == this.treeListColumn减)
            //{
            //    if (!FunctionHelper.IsFloat(e.Value.ToString()) || !FunctionHelper.Is半角(e.Value.ToString()))
            //    {
            //        e.ErrorText = "输入格式不正确！";
            //        e.Valid = false;
            //        return;
            //    }
            //}
        }
        private void barButtonItem文件_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            new Form样品文件(this.formId).ShowDialog();
            this.gridControl备注.DataSource = 样品下单Service.get备注项目详情(this.formId);
        }

        private void 下载文件ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string fileName = FunctionHelper.GetgridViewValue(
                this.gridView备注,
                this.gridView备注.FocusedRowHandle,
                "fileName");
            string filePath = FunctionHelper.GetgridViewValue(
                this.gridView备注,
                this.gridView备注.FocusedRowHandle,
                "filePath");
            if (String.IsNullOrEmpty(fileName))
            {
                MessageBox.Show("暂无文件");
            }
            else
            {
                FolderBrowserDialog sFD = new FolderBrowserDialog();
                DialogResult rdr = sFD.ShowDialog();
                string selectFileName = sFD.SelectedPath;
                if (rdr == System.Windows.Forms.DialogResult.OK && !string.IsNullOrEmpty(selectFileName))
                {
                    try
                    {
                        //通过url下载文件
                        WebClient wClient = new WebClient();
                        wClient.Credentials = System.Net.CredentialCache.DefaultCredentials;
                        wClient.DownloadFile(URL.图片url+"/sample/"+ filePath, selectFileName + "\\" + fileName);
                        MessageBox.Show("保存成功");
                    }
                    catch
                    {
                        MessageBox.Show("保存失败");
                    }
                }
            }

        }
    }
}